<% layout('/layouts/default.html', {title: '收支明细单管理', libs: ['validate','fileupload','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(incomeExpenditure.isNewRecord ? '新增收支明细单' : '编辑收支明细单')}
			</div>
			<div class="box-tools pull-right">
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${incomeExpenditure}" action="${ctx}/financial/incomeExpenditure/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>
				<#form:hidden path="incomeExpenditureId"/>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('单据编号')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="incomeExpenditureCode" readonly="true" placeholder="自动生成" maxlength="100" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('服务订单')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:select path="serviceOrderId" id="serviceOrderId" items="${listServiceOrder}" onchange="jzChange()"
                                itemLabel="serviceOrderCode" itemValue="serviceOrderId" blankOption="true" class="form-control required"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('客户名称')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:select path="customerId" id="customerId" items="${listCustomer}"
                                itemLabel="customerName" itemValue="customerId" blankOption="true" class="form-control required" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('供应商名称')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:select path="supplierId" id="supplierId" items="${listSupplier}"
                                itemLabel="supplierName" itemValue="supplierId" blankOption="true"  class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('外币币种')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:hidden path="currency" id="currencyh" />
                                <#form:select path="currency" id="currency" dictType="sys_bizhong" blankOption="true" class="form-control" disabled="true"  readonly="true" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('外商名称')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:hidden path="foreignBusinessmenId" id="forSupplierh" />
                                <#form:select path="foreignBusinessmenId" id="forSupplier" items="${listSupplier}"
                                itemLabel="supplierName" itemValue="supplierId" blankOption="true" class="form-control" disabled="true" readonly="true" />
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('应收单编号')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:select path="accountingReceivable" items="${listAccountRec}"
                                itemLabel="arCode" itemValue="arId" blankOption="true" class="form-control" readonly="true"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('应付单编号')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
                                <#form:select path="accountingPayable" items="${listAccountPay}"
                                itemLabel="apCode" itemValue="apId" blankOption="true" class="form-control" readonly="true"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required">*</span> ${text('录入类型')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:select path="scannerType" id="scannerType" dictType="erp_scanner_type" blankOption="true" class="form-control required" />
                            </div>
                        </div>
                    </div>
					<!--<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('费用项目')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="expenseItem" dictType="erp_expense_pro" blankOption="true" class="form-control required" />
							</div>
						</div>
					</div>-->
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required">*</span> ${text('费用项目')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:select path="expenseItem" id="expenseItem" items="${listExpenseItem}" onchange="jzChange()"
                                itemLabel="fixedExpenseName" itemValue="fixedExpenseId" blankOption="true" class="form-control required"/>
                            </div>
                        </div>
                    </div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required hide">*</span> ${text('备注信息')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10">
								<#form:textarea path="remarks" rows="4" maxlength="500" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
                <div class="form-unit">${text('车辆明细')} </div>
				<div class="row">
					<div class="col-xs-5">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('收入金额')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="incomeAmount" id="incomeAmount" class="form-control number"/>
							</div>
						</div>
					</div>
					<div class="col-xs-5">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('支出金额')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="expenditureAmount" id="expenditureAmount" class="form-control number"/>
							</div>
						</div>
					</div>
                    <div  class="col-xs-2">
                        <div class="form-group">
                            <button type="button" class="btn btn-primary" id="apportion">${text('金额分配')}</button>
                        </div>
                    </div>
				</div>
                <div class="ml10 mr10">
                    <table id="incomeExpenditureDetailDataGrid"></table>
                    <!--<% if (hasPermi('financial:incomeExpenditure:edit')){ %>
                    <a href="#" id="incomeExpenditureDetailDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10"><i class="fa fa-plus"></i> ${text('增行')}</a>
                    <% } %>-->
                </div>
                <div class="form-unit">${text('附件信息')}</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2">
								<span class="required hide">*</span> ${text('附件上传')}：</label>
							<div class="col-sm-10">
								<#form:fileupload id="uploadFile" bizKey="${incomeExpenditure.id}" bizType="incomeExpenditure_file"
									uploadType="all" class="" readonly="false" preview="true"/>
							</div>
						</div>
					</div>
				</div>
                <div class="form-unit">${text('系统信息')}</div>
                <div class="row">
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required hide">*</span> ${text('创建日期')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:input path="createDate" class="form-control" disabled="true"
                                dataFormat="datetime2" data-type="datetime" data-format="yyyy-MM-dd HH:mm:ss"/>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required hide">*</span> ${text('创建人')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:input path="createBy" class="form-control" disabled="true"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required hide">*</span> ${text('最后修改日期')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:input path="updateDate" readonly="true" maxlength="20" class="form-control"
                                dataFormat="datetime2" data-type="datetime" data-format="yyyy-MM-dd HH:mm:ss"/>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required hide">*</span> ${text('最后修改人')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:input path="updateBy" readonly="true" maxlength="20" class="form-control"/>
                            </div>
                        </div>
                    </div>
                </div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('financial:incomeExpenditure:edit')){ %>
							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>
//初始化收支车辆明细DataGrid对象
$("#incomeExpenditureDetailDataGrid").dataGrid({
	data: ${toJson(incomeExpenditure.incomeExpenditureDetailList)},
	datatype: "local", // 设置本地数据
	autoGridHeight: function(){return 'auto'}, // 设置自动高度

	// 设置数据表格列
	columnModel: [
		{header:'状态', name:'status', editable:true, hidden:true},
		{header:'主键', name:'incomeExpenditureDetailId', editable:true, hidden:true},
		{header:'${text("行号")}', name:'rowNumber', width:100,editable:true, hidden:true},
		{header:'${text("车辆")}', name:'carId', width:100,editable:true, hidden:true},
        {header:'${text("车辆")}', name:'carName', width:300, editable:false, edittype:'text', editoptions:{'maxlength':'64', 'class':'form-control'}},
        {header:'${text("车型")}', name:'model', editable:true, hidden:true},
        {header:'${text("车型")}', name:'model', width:150, editable:false, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control'}},
		{header:'${text("车架号")}', name:'frameNumber', editable:true, hidden:true},
		{header:'${text("车架号")}', name:'frameNumber', width:150, editable:false, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control'}},
		{header:'${text("外币价格")}', name:'foreignCurrencyPrice', editable:true, hidden:true},
		{header:'${text("外币价格")}', name:'foreignCurrencyPrice', width:150, editable:false, edittype:'text', editoptions:{'class':'form-control number'}},
		{header:'${text("收入金额")}', name:'incomeAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number required'}},
		{header:'${text("支出金额")}', name:'expenditureAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number required'}},
		{header:'${text("收支明细单ID")}', name:'incomeExpenditureId.incomeExpenditureId', editable:true, hidden:true},
		{header:'${text("操作")}', name:'actions', width:80, sortable:false, fixed:true, formatter: function(val, obj, row, act){
			var actions = [];
			if (val == 'new'){
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#incomeExpenditureDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}else{
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#incomeExpenditureDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}
			return actions.join('');
		}, editoptions: {defaultValue: 'new'}}
	],

	// 编辑表格参数
	editGrid: true,				// 是否是编辑表格
	editGridInitRowNum: 0,		// 编辑表格的初始化新增行数
	editGridAddRowBtn: $('#incomeExpenditureDetailDataGridAddRowBtn'),	// 子表增行按钮
	editGridAddRowInitData: {incomeExpenditureDetailId: '', status: Global.STATUS_NORMAL},	// 新增行的时候初始化的数据

	// 编辑表格的提交数据参数
	editGridInputFormListName: 'incomeExpenditureDetailList', // 提交的数据列表名
	editGridInputFormListAttrs: 'status,rowNumber,incomeExpenditureDetailId,carId,model,frameNumber,foreignCurrencyPrice,incomeAmount,expenditureAmount,incomeExpenditureId.incomeExpenditureId', // 提交数据列表的属性字段


    /*showFooter: true,	// 是否显示底部合计行
    grouping: true, 	// 是否分组显示
        groupingView: {
        groupField: ["model"], // 需要分组的列
        groupColumnShow: [true],// 是否显示分组的列
        groupText: ["none"],	// 设置组标题，加粗标题：["<b>{0}</b>"]，不显示标题：["none"]
        groupSummary: [false],	// 是否显示[小计]列，数据载入详见 columnModel.formatter
        groupCollapse: false 	// false为默认展开，true默认为折叠
    },*/


	// 加载成功后执行事件
	ajaxSuccess: function(data){
        // 设置底部合计行数据(设置合计行)
       /* $('#incomeExpenditureDetailDataGrid').dataGrid("footerData", "set", {
            'frameNumber' : '<em>合计：&nbsp;</em>',
            'incomeAmount': "<em>" + data.count + "</em>",
            'expenditureAmount': '<em>￥1000 &nbsp;</em>'
        }, false);*/
	}
});
</script>
<script>
$("#inputForm").validate({
	submitHandler: function(form){
		js.ajaxSubmitForm($(form), function(data){
			js.showMessage(data.message);
			if(data.result == Global.TRUE){
				js.closeCurrentTabPage(function(contentWindow){
					contentWindow.page();
				});
			}
		}, "json");
    }
});

$("#apportion").click(function () {
    var allIds = $('#incomeExpenditureDetailDataGrid').dataGrid('getDataIDs');
    // 先保存单据
    for (var i = 0; i < allIds.length ; i++) {
        $('#incomeExpenditureDetailDataGrid').dataGrid('saveRow', allIds[i], true);
    }
   var  allData = $('#incomeExpenditureDetailDataGrid').dataGrid('getRowData');
   // 取外币总数
    var allForeignCurrencyPrice = 0;
    for (var i = 0; i <allData.length ; i++) {
        allForeignCurrencyPrice = calcAdd(allForeignCurrencyPrice,zeroZhuan(allData[i].foreignCurrencyPrice));
    }
    // js.log("allForeignCurrencyPrice="+allForeignCurrencyPrice);
    // 算每行的比例
    var dataArr = [];
    for (var i = 0; i < allData.length ; i++) {
        dataArr.push(calcDiv(allData[i].foreignCurrencyPrice,allForeignCurrencyPrice));
    }
    // js.log(dataArr)
    var incomeAmount = zeroZhuan($('#incomeAmount').val());
    var expenditureAmount =zeroZhuan( $('#expenditureAmount').val());
    // 分配赋值
	var sum1 = 0;
	var sum2 = 0;
    for (var i = 0; i < allData.length ; i++) {
        var income = calcMul(dataArr[i],incomeAmount).toFixed(4);
        var expend = calcMul(dataArr[i],expenditureAmount).toFixed(4);
        // js.log("income="+income   +"   "+"expend="+expend);
		if(i == allData.length-1){
			income = calcSub(parseFloat(incomeAmount).toFixed(4),sum1);
			expend = calcSub(parseFloat(expenditureAmount).toFixed(4),sum2);
		}
		sum1 = calcAdd(sum1,income);
		sum2 = calcAdd(sum2,expend);
        $('#incomeExpenditureDetailDataGrid').dataGrid('setRowData', allIds[i],{incomeAmount:income,expenditureAmount:expend});
        $("#incomeExpenditureDetailDataGrid").dataGrid("editRow", allIds[i], {keys: true});
    }
});


function jzChange() {
    var serviceOrderId = $("#serviceOrderId").val();
    var expenseItem = $("#expenseItem").val();
    if (serviceOrderId && expenseItem){
        var url = "${ctx}/order/serviceorder/serviceOrder/getOneByIdAndExpend?serviceOrderId="+serviceOrderId +"&expenseItem="+expenseItem;
        $.post(url,null,function (result) {
           /* $("#customerId").val("").trigger("change");
            $("#supplierId").val("").trigger("change");
            $("#currency").val("").trigger("change");
            $("#forSupplier").val("").trigger("change");*/
            // js.log(result);
            var customer = result.customer.customerId;
            var investor = result.investor.supplierId;
            var currency = result.currency;
            var foreignBusinessmen = result.foreignBusinessmen.supplierId;
            var list = result.serviceOrderDetailList;
            $("#customerId").val(customer).trigger("change");
            $("#supplierId").val(investor).trigger("change");
            $("#currency").val(currency).trigger("change");
            $("#currencyh").val(currency).trigger("change");
            $("#forSupplier").val(foreignBusinessmen).trigger("change");
            $("#forSupplierh").val(foreignBusinessmen).trigger("change");

            // 子表赋值
            var allIds = $('#incomeExpenditureDetailDataGrid').dataGrid('getDataIDs');
            for (var i = 0; i < allIds.length ; i++) {
                if (allIds[i].length < 10){
                    $('#incomeExpenditureDetailDataGrid').dataGrid('delRowData',allIds[i]);
                }else {
                    $('#incomeExpenditureDetailDataGrid').dataGrid('setRowData',allIds[i],null,{display:"none"});
                    $('#'+allIds[i]+'_status').val(Global.STATUS_DELETE);
                }
            }
            for (var i = 0; i < list.length; i++) {
                var carId = list[i].carId;
                var carName = list[i].tcar.carName;
                var model = list[i].model;
                var amount = list[i].amount;
                var frameNumber = list[i].frameNumber;
                var rowNumber = list[i].rowNumber;
                $("#incomeExpenditureDetailDataGrid").jqGrid("addRow", {
                    position: "last",
                    addRowParams: {keys: false, focusField: true},
                    initdata: {id: "", status: Global.STATUS_NORMAL,rowNumber: rowNumber, carId: carId, carName: carName, model: model, frameNumber: frameNumber,foreignCurrencyPrice:amount}
                });
            }
            if (typeof window.webuploaderRefresh == 'function'){
                window.webuploaderRefresh();
            }
        });
    }
};
</script>

<script>

    /**
     * 加法函数
     *
     * @param arg1
     * @param arg2
     * @returns {number}
     */
    function calcAdd(arg1, arg2) {
        var r1, r2, m, c;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        c = Math.abs(r1 - r2);
        m = Math.pow(10, Math.max(r1, r2));
        if (c > 0) {
            var cm = Math.pow(10, c);
            if (r1 > r2) {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", "")) * cm;
            } else {
                arg1 = Number(arg1.toString().replace(".", "")) * cm;
                arg2 = Number(arg2.toString().replace(".", ""));
            }
        } else {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", ""));
        }
        return (arg1 + arg2) / m;
    }

    /**
     * 减法函数
     *
     * @param arg1
     * @param arg2
     * @returns {String}
     */
    function calcSub(arg1, arg2) {
        var r1, r2, m, n;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2)); // last modify by deeka //动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);

    }

    /**
     * 乘法函数
     *
     * @param arg1
     * @param arg2
     * @returns {Number}
     */
    function calcMul(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length
        } catch (e) {
        }
        try {
            m += s2.split(".")[1].length
        } catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    }

    /**
     * 除法函数
     *
     * @param arg1
     * @param arg2
     * @returns {Number}
     */
    function calcDiv(arg1, arg2) {
        var t1 = 0, t2 = 0, r1, r2;
        try {
            t1 = arg1.toString().split(".")[1].length;
        } catch (e) {
        }
        try {
            t2 = arg2.toString().split(".")[1].length;
        } catch (e) {
        }
        with (Math) {
            r1 = Number(arg1.toString().replace(".", ""));
            r2 = Number(arg2.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    }

    /**
     * Null 转换成 0
     *
     * @param data
     * @returns {number}
     * @constructor
     */
    function zeroZhuan(data) {
        return data ? data : 0;
    }
</script>


